/**
 * Copyright (c) 2011 eelpo.com
 * All rights reserved.
 */
package com.eelpo.cmmp.core.wicket.resource;

import java.io.Serializable;

import com.eelpo.common.util.DateFormatUtils;

/**
 * <pre>
 * 
 * 验证码对象
 * 
 * </pre>
 * 
 * @author <a href="mailto:Brian@eelpo.com">汪洪州</a>
 * @since 1.0
 */
public class Captcha implements Serializable {

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = -4780420044199305323L;

	private String expected;
	/**
	 * 口令
	 */
	private String actual;

	/**
	 * 建立时间
	 */
	private long genarate = DateFormatUtils.getTimeMillis();

	/**
	 * 超时时间
	 */
	private long timeout;

	/**
	 * 默认过期时间，单位秒
	 */
	private static final long DEFAULT_TIMEOUT = 30;

	/**
	 * 构造函数，默认30秒过期
	 */
	public Captcha() {
		this(DEFAULT_TIMEOUT);
	}

	/**
	 * 构造函数，设置超时时间（单位：秒）
	 * 
	 * @param timeout
	 */
	public Captcha(long timeout) {
		this.timeout = timeout;
	}

	public void verify(String actual) throws VerifyExcpetion {
		setActual(actual);
		verify();
	}

	public void verify() throws VerifyExcpetion {

		if (!expected.equalsIgnoreCase(getActual())) {
			throw new VerifyExcpetion("验证码输入错误！");
		}

		if ((getGenarate() + (getTimeout() * 1000)) - DateFormatUtils.getTimeMillis() < 0) {
			throw new VerifyExcpetion("验证码超过[" + getTimeout() + "]秒已过期！");
		}
	}

	public String getExpected() {
		return expected;
	}

	public void setExpected(String expected) {
		this.expected = expected;
	}

	public String getActual() {
		return actual;
	}

	public void setActual(String actual) {
		this.actual = actual;
	}

	public long getGenarate() {
		return genarate;
	}

	public long getTimeout() {
		return timeout;
	}

	public void setTimeout(long timeout) {
		this.timeout = timeout;
	}

	public void clear() {
		this.actual = null;
		this.expected = null;
	}
}
